<template>
  <div class="device-tree-table">
    <!-- 顶部搜索 -->
    <AssessmentDialog
      v-model:visible="dialogVisible"
      :mode="dialogMode"
      :rowData="currentRow"
      @success="loadAllDevices"
    />
    <SearchFilters @search="onSearch" />

    <!-- 树形表格 -->
    <el-table
      v-if="treeRows.length"
      :data="treeRows"
      row-key="id"
      :tree-props="{ children: 'children' }"
      border
      height="600"
      style="width: 100%"
    >
      <!-- 设备名称 -->
      <el-table-column prop="name" label="名称" min-width="200" />

      <!-- 保留上一级名称列 -->
<el-table-column prop="parentName" label="设备名称" min-width="180">
  <template #default="{ row }">
    <el-input v-model="row.parentName" placeholder="设备名称" />
  </template>
</el-table-column>

<!-- 初始日期 -->
<el-table-column prop="initialDate" label="初始日期" min-width="140">
  <template #default="{ row }">
    <el-date-picker
      v-model="row.initialDate"
      type="date"
      value-format="YYYY-MM-DD"
      placeholder="选择日期"
      style="width: 100%"
    />
  </template>
</el-table-column>

<!-- 分数 -->
<el-table-column prop="score" label="分数" min-width="100">
  <template #default="{ row }">
    <el-input v-model="row.score" placeholder="请输入分数" />
  </template>
</el-table-column>

<!-- 维护工种 -->
<el-table-column prop="maintainType" label="维护工种" min-width="180">
  <template #default="{ row }">
    <el-select
      v-model="row.maintainType"
      multiple
      clearable
      filterable
      placeholder="选择维护工种"
      collapse-tags
      style="width: 100%"
    >
      <el-option
        v-for="dict in asset_trade_code"
        :key="dict.value"
        :label="dict.label"
        :value="parseInt(dict.value)"
      />
    </el-select>
  </template>
</el-table-column>

<!-- 备件数量 -->
<el-table-column prop="spareCount" label="备件数量" min-width="120">
  <template #default="{ row }">
    <el-input v-model="row.spareCount" placeholder="数量" />
  </template>
</el-table-column>

<!-- 计划内容 -->
<el-table-column prop="planContent" label="计划内容" min-width="220">
  <template #default="{ row }">
    <el-input
      v-model="row.planContent"
      type="textarea"
      :rows="2"
      placeholder="请输入计划内容"
    />
  </template>
</el-table-column>

<!-- 风险评分类 -->
<el-table-column prop="standby" label="STANDBY" min-width="120">
  <template #default="{ row }">
    <el-input v-model="row.standby" placeholder="输入" />
  </template>
</el-table-column>
<el-table-column prop="quality" label="QUALITY" min-width="120">
  <template #default="{ row }">
    <el-input v-model="row.quality" placeholder="输入" />
  </template>
</el-table-column>
<el-table-column prop="safetyHealth" label="SAFETY/HEALTH" min-width="140">
  <template #default="{ row }">
    <el-input v-model="row.safetyHealth" placeholder="输入" />
  </template>
</el-table-column>
<el-table-column prop="environment" label="ENVIRONMENT" min-width="140">
  <template #default="{ row }">
    <el-input v-model="row.environment" placeholder="输入" />
  </template>
</el-table-column>
<el-table-column prop="impact" label="IMPACT" min-width="120">
  <template #default="{ row }">
    <el-input v-model="row.impact" placeholder="输入" />
  </template>
</el-table-column>
<el-table-column prop="criticalLevel" label="CRITICAL LEVEL" min-width="140">
  <template #default="{ row }">
    <el-input v-model="row.criticalLevel" placeholder="输入" />
  </template>
</el-table-column>
<el-table-column prop="cost" label="COST" min-width="100">
  <template #default="{ row }">
    <el-input v-model="row.cost" placeholder="输入" />
  </template>
</el-table-column>

<!-- 是否处理 -->
<el-table-column prop="isDeal" label="是否处理" min-width="120">
  <template #default="{ row }">
    <el-select v-model="row.isDeal" placeholder="请选择">
      <el-option label="未处理" :value="0" />
      <el-option label="已处理" :value="1" />
    </el-select>
  </template>
</el-table-column>

<el-table-column prop="isEnterPart" label="是否进入备件库" min-width="120">
  <template #default="{ row }">
    <el-select v-model="row.isDeal" placeholder="请选择">
      <el-option label="不进入" :value="0" />
      <el-option label="进入" :value="1" />
    </el-select>
  </template>
</el-table-column>

<!-- 删除状态 -->
<el-table-column prop="isDelete" label="删除状态" min-width="120">
  <template #default="{ row }">
    <el-select v-model="row.isDelete" placeholder="请选择状态">
      <el-option
        v-for="dict in asset_delete"
        :key="dict.value"
        :label="dict.label"
        :value="parseInt(dict.value)"
      />
    </el-select>
  </template>
</el-table-column>

<!-- 备注 -->
<el-table-column prop="remark" label="备注" min-width="200">
  <template #default="{ row }">
    <el-input v-model="row.remark" type="textarea" :rows="2" placeholder="备注" />
  </template>
</el-table-column>

 

      

      <!-- 类型 -->
      <el-table-column prop="nodeType" label="类型" width="100">
        <template #default="{ row }">
          <el-tag size="small" :type="tagType(row.nodeType)">
            {{ typeLabel(row.nodeType) }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button  type="success" link size="small" @click="saveRow(row)">
            保存
          </el-button>
          <el-button type="warning" link size="small" @click="clearRow(row)">
            清空
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty v-else description="暂无数据" class="empty-block" />

    <!-- 分页 -->
    <div class="tree-pagination" v-if="totalRoots > pageSize">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper, sizes"
        :total="totalRoots"
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20,50]"
        @current-change="noop"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import SearchFilters from './SearchFilters.vue'
import { listSbtz } from '@/api/sbtz/sbtz'
import AssessmentDialog from '@/components/sbtz/assessment/AssessmentDialog.vue'
import { listAssessment, getAssessment, delAssessment, addAssessment, updateAssessment } from "@/api/sbtz/assessment"
const { proxy } = getCurrentInstance();
const { asset_trade_code, asset_delete } = proxy.useDict('asset_trade_code', 'asset_delete');

/** 分页与状态管理 */
const allRoots = ref([])
const fullData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const totalRoots = ref(0)
const dialogVisible = ref(false)
const dialogMode = ref('add')
const currentRow = ref({})


 

/** 类型映射 */
function typeLabel(type) {
  const map = {
    SYSTEM: '系统',
    MACHINE: '母设备',
    MODULE: '子设备',
    COMPONENT: '部件',
    PART: '零件',
    SPARE: '备件',
  }
  return map[type] || '备件'
}
function tagType(type) {
  return {
    MACHINE: 'primary',
    MODULE: 'success',
    COMPONENT: 'info',
    PART: 'warning',
    SPARE: 'danger',
  }[type] || 'default'
}

/** 初始化加载完整数据 */
async function loadAllDevices() {
  const { rows = [] } = await listSbtz({ pageNum: 1, pageSize: 5000 });
  const filtered = rows.filter(r => r.nodeType !== 'SYSTEM').map(item => ({
    ...item,
    isEnterPart: item.isEnterPart ?? 0, // 确保每个节点都有 isEnterPart
  }));
  const map = new Map();
  filtered.forEach(f => map.set(f.id, { ...f, children: [] }));
  const roots = [];
  filtered.forEach(f => {
    const cur = map.get(f.id);
    if (!f.parentId || !map.has(f.parentId)) roots.push(cur);
    else map.get(f.parentId).children.push(cur);
  });
  roots.forEach(d => attachRealSpares(d));
  fullData.value = roots;
  allRoots.value = roots;
  totalRoots.value = roots.length;
}


// 替换你现有的 clearRow
function clearRow(row) {
  // 仅重置可编辑字段；结构字段（id/name/nodeType/children等）不动
  const defaults = {
    // 本页评估相关字段
    parentName: '',
    initialDate: '',
    score: '',
    maintainType: [],
    spareCount: '',
    planContent: '',
    standby: '',
    quality: '',
    safetyHealth: '',
    environment: '',
    impact: '',
    criticalLevel: '',
    cost: '',
    isDeal: 0,
    isDelete: 0,
    isEnterPart: 0,
    remark: '',

    // 如行里带有备件字段（兼容你之前的列）
    code: '',
    spareClass: null,
    amount: 0,
    vendor: '',
    spec: '',
    material: ''
  };

  Object.keys(defaults).forEach(k => {
    // 深拷贝一下，避免复用引用类型
    row[k] = JSON.parse(JSON.stringify(defaults[k]));
  });

  ElMessage.success('已清空该行');
}



/** 兼容 spareInfos → 转为子节点 */
function attachRealSpares(node) {
  if (!node) return
  node.children = Array.isArray(node.children) ? node.children : []
  const spares = Array.isArray(node.spareInfos) ? node.spareInfos : []
  spares.forEach((s, idx) => {
    node.children.push({
      id: `spare:${node.id}:${s.id ?? idx}`,
      ...s,
      nodeType: 'SPARE',
      spareClass: s.spareClass ?? 1,
      amount: s.amount ?? 0,
      vendor: s.vendor ?? '',
      spec: s.spec ?? '',
      assetId: node.id,
      isEnterPart: s.isEnterPart ?? 0,
    })
  })
  node.children.forEach(ch => {
    if (ch.nodeType !== 'SPARE') attachRealSpares(ch)
  })
}

/** 行内保存 */
/** 行内保存 */
async function saveRow(row) {
  // 验证必填字段
  if (!row.name?.trim()) {
    return ElMessage.warning('请填写设备名称');
  }

  console.log(row);
  try {
    let maintainTypeData = row.maintainType || [];
    
    // 准备保存的数据
    const data = {
      assetId: row.id ?? 0, // 新增备件时不传ID 
      initialDate: row.initialDate || '',
      score: row.score || '',
      maintainType: JSON.stringify(maintainTypeData),
      spareCount: row.spareCount || '',
      planContent: row.planContent || '',
      standby: row.standby || '',
      quality: row.quality || '',
      safetyHealth: row.safetyHealth || '',
      environment: row.environment || '',
      impact: row.impact || '',
      criticalLevel: row.criticalLevel || '',
      cost: row.cost || '',
      isDeal: row.isDeal || 0,
      isEnterPart: row.isEnterPart || 0, 
      remark: row.remark || '',
      spareClass: row.nodeType, // 默认为备件类型 
    };

    // 判断是新增还是更新
    let response = await addAssessment(data);
    // let response;
    // if (row.id) {
    //   // 更新现有记录
    //   response = await updateAssessment(data);
    // } else {
    //   // 新增记录
    //   response = await addAssessment(data);
    // }

    // 保存成功提示
    ElMessage.success(`已保存 ${row.name}`);

    // 刷新列表
    await loadAllDevices();

  } catch (error) {
    // 错误处理
    console.error('保存失败:', error);
    ElMessage.error('保存失败，请稍后重试');
  }
}


function deleteRow(row) {
  console.log('删除行', row)
  ElMessage.success(`已删除 ${row.name}`)
}

/** 搜索逻辑保持原样 */
async function onSearch(params) {
  if (!params.muName && !params.keyword) {
    allRoots.value = fullData.value
    totalRoots.value = allRoots.value.length
    return
  }
  const { rows: matched = [] } = await listSbtz({
    id: params.muName || null,
    keyword: params.keyword || null,
    pageNum: 1,
    pageSize: 1000
  })
  if (!matched.length) {
    allRoots.value = []
    totalRoots.value = 0
    return
  }
  const { rows: all = [] } = await listSbtz({ pageNum: 1, pageSize: 5000 })
  const allFiltered = all.filter(r => r.nodeType !== 'SYSTEM')
  const idSet = new Set()
  const result = []
  function addNodeById(id) {
    if (idSet.has(id)) return
    const node = allFiltered.find(n => n.id === id)
    if (!node) return
    idSet.add(id)
    result.push(node)
    allFiltered.filter(n => n.parentId === id).forEach(ch => addNodeById(ch.id))
  }
  matched.forEach(root => addNodeById(root.id))
  allRoots.value = buildTree(result)
  totalRoots.value = allRoots.value.length
  pageNum.value = 1
}
function buildTree(rows = []) {
  const filtered = rows.filter(r => r.nodeType !== 'SYSTEM')
  const map = new Map()
  filtered.forEach(f => map.set(f.id, { ...f, children: [] }))
  const roots = []
  filtered.forEach(f => {
    const cur = map.get(f.id)
    if (!f.parentId || !map.has(f.parentId)) roots.push(cur)
    else map.get(f.parentId).children.push(cur)
  })
  roots.forEach(d => attachRealSpares(d))
  return roots
}

/** 分页 */
const treeRows = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allRoots.value.slice(start, end)
})
function handleSizeChange() { pageNum.value = 1 }
function noop() {}

onMounted(() => loadAllDevices())
</script>

<style scoped>
.device-tree-table {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 10px 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.tree-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
.empty-block {
  height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.el-input,
.el-input-number,
.el-select {
  width: 100%;
}
</style>
